package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DoubleUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.Cleaner;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/system/stat")
public class SysStatController extends BaseController {

    private String prefix = "system/stat";

    @Autowired
    private ISysTenantBacklogService sysTenantBacklogService;

    @Autowired
    private ISysBuildingService sysBuildingService;

    @Autowired
    private ISysUnitService sysUnitService;

    @Autowired
    private ISysExpenseMergeService sysExpenseMergeService;

    @Autowired
    private ISysTenantService sysTenantService;

    @Autowired
    private ISysHigherService sysHigherService;


    /*
    * 首页已（待）涨租显示框
    * */

    @RequiresPermissions("system:stat:view")
    @GetMapping()
    public String st(ModelMap mmap)
    {
        startPage();
        SysTenant sysTenant = new SysTenant();
        SysHigher sysHigher = new SysHigher();
        sysTenant.setRisePriceStatus(HigherStatus.WAIT.getCode());
        sysTenant.setTenantStatus(TenantStatus.LIVEING.getCode());
        List<SysTenant> listNot = sysTenantService.selectSysTenantHigherList(sysTenant);
        List<SysHigher> listAlread = sysHigherService.selectSysHigherLogList(sysHigher);
        mmap.put("listAlread",listAlread);
        mmap.put("listNot",listNot);
        return prefix + "/stat";
    }



    /**
     * 首页统计数据返回
     * @return
     */
    @PostMapping("/statData")
    @ResponseBody
    public AjaxResult statData() {
        //TODO
        Map allMap = new HashMap();
        //本月已收租列表
        List<SysExpenseMerge> expenseMergeAlready = sysExpenseMergeService.selectSysExpenseMergeMonthList(null);
        //本月应收租列表
        List<SysTenantBacklog> backlogListAll = sysTenantBacklogService.selectSysTenantBacklogMonthList(null);
        //各楼栋未收金额集合
        List<SysTenantBacklog> backlogStatList = sysTenantBacklogService.selectSysTenantBacklogStatList();

        //各楼栋空闲单元和在租单元集合
        List<SysUnit> findUnitList = sysUnitService.selectSysUnitStatList();


//        ==================================================模块一=====================================================
        double monShould = 0,//本月应收
                monAlready = 0;// 本月已收

        int monTenant = 0,     //本月已收户数
            TenantNot = 0;      //本月未缴户数

        int monTenantNum = 0;
        //本月已收
        for (SysExpenseMerge sysExpenseMerge : expenseMergeAlready) {
            monAlready += Double.parseDouble(sysExpenseMerge.getRealMonthlyRentFee());
        }
        //本月应收
        for (SysTenantBacklog tenantBacklog : backlogListAll) {
            if(tenantBacklog.getHigherRentFee()!=null){
                monShould += Double.parseDouble(tenantBacklog.getHigherRentFee());
            }
        }
        //本月未收
//        for (SysTenantBacklog sysTenantBacklog : backlogStatList) {
//            monNot += sysTenantBacklog.getNumber();
//        }

        //收费租户
        monTenant = expenseMergeAlready.size();

        for(SysUnit findunitList:findUnitList){
            if (findunitList.getUnitStatus().equals(UnitStatus.RENTING.getCode())) {
                //在租单元数
                monTenantNum += findunitList.getNumber();
            }
        }
        TenantNot = monTenantNum - monTenant;

        //模块一数据Map
        Map modelOne = new HashMap();
        modelOne.put("monShould", DoubleUtil.round(monShould, 2));
        modelOne.put("monAlready", DoubleUtil.round(monAlready, 2));
        modelOne.put("TenantNot", TenantNot);
        modelOne.put("monTenant", monTenant);
        allMap.put("modelOne", modelOne);

//        ==================================================模块二=====================================================
        //各楼栋空闲单元和在租单元集合
        List<SysUnit> unitList = sysUnitService.selectSysUnitStatList();
        //各楼栋已收金额集合
        List<SysExpenseMerge> expenseMerges = sysExpenseMergeService.selectSysExpenseMergeStatList();
        //统计-楼栋集合
        List<SysBuilding> buildingList = sysBuildingService.selectSysBuildingAll();
        //各个楼栋已缴费户数
        List<SysExpenseMerge> unitCountList = sysExpenseMergeService.selectSysExpenseMergeCount();


        List<SysStatModelTwo> modelTwoList = new ArrayList<>();
        for (SysBuilding sysBuilding : buildingList) {
            SysStatModelTwo statModelTwo = new SysStatModelTwo();
            //楼栋名
            statModelTwo.setBulidingName(sysBuilding.getBuildingName() + "栋租户情况");
            for (SysUnit sysUnit : unitList) {
                if (sysUnit.getBuildingName().equals(sysBuilding.getBuildingName())) {
                    if (sysUnit.getUnitStatus().equals(UnitStatus.FREE.getCode()) || sysUnit.getUnitStatus().equals(UnitStatus.WILL.getCode())) {
                        //空闲单元数
                        statModelTwo.setUnitFree(sysUnit.getNumber());
                    }
                    if (sysUnit.getUnitStatus().equals(UnitStatus.RENTING.getCode())) {
                        //在租单元数
                        statModelTwo.setUnitRenting(sysUnit.getNumber());
                    }
                }
            }

            for (SysExpenseMerge sysExpenseMerge : unitCountList) {
                //已缴费用户
                if (sysExpenseMerge.getBuildingName().equals(sysBuilding.getBuildingName())) {
                    statModelTwo.setTenantAlready(sysExpenseMerge.getCount());
                }
            }

            for (SysExpenseMerge expenseMerge : expenseMerges) {
                if (expenseMerge.getBuildingName().equals(sysBuilding.getBuildingName())) {
                    //已收租金额
                    statModelTwo.setAlreadyFee(DoubleUtil.round(expenseMerge.getNumber(), 2));
                }
            }
                modelTwoList.add(statModelTwo);
        }
        allMap.put("modelTwo", modelTwoList);

        //        ==================================================模块三=====================================================
        //当前年份
        String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        List<String> dateList = Arrays.asList("1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月");
        List<SysExpenseMerge> expenseMergeList = sysExpenseMergeService.selectSysExpenseMergeStatListForMonth();
        List<SysExpenseMerge> expenseMergeListAll = sysExpenseMergeService.selectSysExpenseMergeStatListForMonthAll();

        List buildingSum = new ArrayList<String>();                 //每个月份的总金额
        List buildingA = new ArrayList<String>(Arrays.asList("0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"));       //每个月份的A栋总金额
        List buildingB = new ArrayList<String>(Arrays.asList("0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"));      //每个月份的B栋总金额
        List buildingC = new ArrayList<String>(Arrays.asList("0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"));      //每个月份的C栋总金额
        List buildingD = new ArrayList<String>(Arrays.asList("0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"));      //每个月份的D栋总金额

        Boolean check;
        for (String date : dateList) {
            check = true;
                    for (SysExpenseMerge expenseMerge : expenseMergeListAll) {
                if(expenseMerge.getStatTime().equals(changeDate(date))){
                    buildingSum.add(new BigDecimal(expenseMerge.getNumber()).setScale(2,
                            BigDecimal.ROUND_HALF_UP).doubleValue());
                    check = false;
                }
            }
            if(check){
                buildingSum.add("0");
            }
        }


        for (SysExpenseMerge expenseMerge : expenseMergeList) {


            if (expenseMerge.getBuildingName().equals("A")) {

                if (expenseMerge.getStatTime().substring(0, 4).equals(year)) {
                    buildingA.set(changDate(expenseMerge.getStatTime()) - 1,
                            new BigDecimal(expenseMerge.getNumber()+"").setScale(2,
                                    BigDecimal.ROUND_HALF_UP).doubleValue());
                }         //每个月A栋总金额

            }
            if (expenseMerge.getBuildingName().equals("B")) {
                if (expenseMerge.getStatTime().substring(0, 4).equals(year)) {
                    buildingB.set(changDate(expenseMerge.getStatTime()) - 1,
                            new BigDecimal(expenseMerge.getNumber()+"").setScale(2,
                                    BigDecimal.ROUND_HALF_UP).doubleValue());
                }           //每个月B栋总金额

            }
            if (expenseMerge.getBuildingName().equals("C")) {
                if (expenseMerge.getStatTime().substring(0, 4).equals(year)) {
                    buildingC.set(changDate(expenseMerge.getStatTime()) - 1,
                            new BigDecimal(expenseMerge.getNumber()+"").setScale(2,
                                    BigDecimal.ROUND_HALF_UP).doubleValue());
                }           //每个月C栋总金额

            }
            if (expenseMerge.getBuildingName().equals("D")) {
                if (expenseMerge.getStatTime().substring(0, 4).equals(year)) {
                    buildingD.set(changDate(expenseMerge.getStatTime()) - 1,
                            new BigDecimal(expenseMerge.getNumber()+"").setScale(2,
                                    BigDecimal.ROUND_HALF_UP).doubleValue());
                }           //每个月D栋总金额
            }

        }


        Map threeMap = new HashMap();
        //月份数组
        threeMap.put("dateList", dateList);
        //A月显示金额
        threeMap.put("buildingA", buildingA);
        //B月显示金额
        threeMap.put("buildingB", buildingB);
        //C月显示金额
        threeMap.put("buildingC", buildingC);
        //D月显示金额
        threeMap.put("buildingD", buildingD);
        //各月金额数组
        threeMap.put("buildingSum", buildingSum);

//        threeMap.put("expenseList",expenseList);
        allMap.put("modelThree", threeMap);
        return AjaxResult.success(allMap);
    }



//


//
//        //        ==================================================模块五=====================================================
//        //首页实收租金一览
//        //当前年份
    /**
     * 首页统计数据返回
     * @return
     */
    @PostMapping("/statDataAlraedy")
    @ResponseBody
    public AjaxResult statDataAlraedy() {
        Map allMap = new HashMap();
        String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        List<String> dateList = Arrays.asList("1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月");
        List<SysExpenseMerge> expenseMergeListTwo = sysExpenseMergeService.selectSysExpenseMergeStatListForMonthAlready();
        List<SysExpenseMerge> expenseMergesTwo = sysExpenseMergeService.selectSysExpenseMergeStatListForMonthAlreadyAll();
//        Boolean check;
        List buildingSumAlready = new ArrayList<String>();                 //每个月份的总金额
        List buildingaAlready = new ArrayList<String>(Arrays.asList("0","0","0","0","0","0","0","0","0","0","0","0"));
        List buildingbAlready = new ArrayList<String>(Arrays.asList("0","0","0","0","0","0","0","0","0","0","0","0"));
        List buildingcAlready = new ArrayList<String>(Arrays.asList("0","0","0","0","0","0","0","0","0","0","0","0"));
        List buildingdAlready = new ArrayList<String>(Arrays.asList("0","0","0","0","0","0","0","0","0","0","0","0"));


        Boolean check;
        for (String date : dateList) {
            check = true;
            for (SysExpenseMerge expenseMerge : expenseMergesTwo) {
                if(expenseMerge.getStatTime().equals(changeDate(date))){
                    buildingSumAlready.add(new BigDecimal(expenseMerge.getNumber()).setScale(2,
                            BigDecimal.ROUND_HALF_UP).doubleValue());
                    check = false;
                }
            }
            if(check){
                buildingSumAlready.add("0");
            }
        }



        for(SysExpenseMerge expenseMerge:expenseMergeListTwo) {

            if (expenseMerge.getBuildingName().equals("A")){
                if(expenseMerge.getStatTime().substring(0,4).equals(year)){
                    buildingaAlready.set(changDate(expenseMerge.getStatTime())-1,expenseMerge.getNumber());
                }

            }
            if (expenseMerge.getBuildingName().equals("B")){
                if(expenseMerge.getStatTime().substring(0,4).equals(year)){
                    buildingbAlready.set(changDate(expenseMerge.getStatTime())-1,expenseMerge.getNumber());
                }

            }
            if (expenseMerge.getBuildingName().equals("C")){
                if(expenseMerge.getStatTime().substring(0,4).equals(year)){
                    buildingcAlready.set(changDate(expenseMerge.getStatTime())-1,expenseMerge.getNumber());
                }

            }
            if (expenseMerge.getBuildingName().equals("D")){
                if(expenseMerge.getStatTime().substring(0,4).equals(year)){
                    buildingdAlready.set(changDate(expenseMerge.getStatTime())-1,expenseMerge.getNumber());
                }
            }



        }
        Map fiveMap = new HashMap();
        //月份数组
        fiveMap.put("dateList",dateList);
        //A月显示金额
        fiveMap.put("buildingaAlready",buildingaAlready);
        //B月显示金额
        fiveMap.put("buildingbAlready",buildingbAlready);
        //C月显示金额
        fiveMap.put("buildingcAlready",buildingcAlready);
        //D月显示金额
        fiveMap.put("buildingdAlready",buildingdAlready);
        //各月金额数组
        fiveMap.put("buildingSumAlready",buildingSumAlready);

//        fourMap.put("expenseList",expenseList);
        allMap.put("modelfive",fiveMap);
        return AjaxResult.success(allMap);


    }


    //时间转换为索引 例如：2020-01转换为1；2020-10转换成10
    public int changDate(String date) {
        try {
            Date d1 = new SimpleDateFormat("yyyy-MM").parse(date);
            SimpleDateFormat sdf1 = new SimpleDateFormat("MM");
            String str2 = sdf1.format(d1);
            return Integer.parseInt(str2);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return 1;
    }
    // 字符串拼接：例如：7月转换成:2020-07

    public String changeDate(String date){
        //当前年份
        String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        String newDate = date.replace("月","");
        String a =year+"-";
        String b ;
        if (newDate.length()>1){
            b= a.concat(newDate);
        }else {
            b= a.concat("0").concat(newDate);
        }
        return b;
    }
    public String changeDateTwo(String date) {
        //当前年份
        String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        String newDate = date.replace("月", "");
        String a =year+"-";
        String b;
        if (newDate.length() > 1) {
            b = a.concat(newDate);
        } else {
            b = a.concat("0").concat(newDate);
        }
        return b+"-01";
    }



//









    //        ==================================================模块四=====================================================
    //待涨租预警
    /**
     * 确认涨租
     */
    @RequiresPermissions("system:higher:confirm")
    @Log(title = "确认涨租", businessType = BusinessType.INSERT)
    @PostMapping("/confirm")
    @ResponseBody
    public AjaxResult confirm(SysTenant sysTenant) {

        SysTenant realTenant = sysTenantService.selectSysTenantById(sysTenant.getTenantId());
        // 原先涨租时间
        Date originRisePriceFirstTime = realTenant.getRisePriceFirstTime();
        Calendar cal = Calendar.getInstance();
        cal.setTime(originRisePriceFirstTime);
        cal.add(Calendar.YEAR, 1);//增加一年
        // 涨租一年的时间
        Date newRisePriceTime = cal.getTime();
        realTenant.setNextHigherTime(newRisePriceTime);
        // 更新
        sysTenantService.updateSysTenant(realTenant);


        SysHigher sysHigher = new SysHigher();
        sysHigher.setTenantId(sysTenant.getTenantId());

        Double higherRentFee = Double.parseDouble(sysTenant.getMonthlyRentFee()) * (1 + Double.parseDouble(sysTenant.getRisePriceRatio()));
        sysHigher.setHigherRentFee(higherRentFee);
        sysHigher.setCreateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();

        return toAjax(sysHigherService.insertSysHigher(sysHigher));
    }


    //        ==================================================模块六=====================================================
//十大租户
    /**
     * 首页十大租户数据返回
     * @return
     */
    @PostMapping("/statDataTenTenant")
    @ResponseBody
    public AjaxResult statDataTeTenant(){
        Map allMap = new HashMap();
        List<String> tenTenantName = new ArrayList<String>(10);
        List<BigDecimal> tenTenantMoney = new ArrayList<>(10);
        List<SysExpenseMerge> expenseMergesListSix = sysExpenseMergeService.selectSysExpenseMergeStatListForTenTenant();

            for(SysExpenseMerge expenseMerge:expenseMergesListSix){
                tenTenantName.add(expenseMerge.getTenantName());
                tenTenantMoney.add(new BigDecimal(expenseMerge.getMonthlyRentFee()).setScale(2,BigDecimal.ROUND_HALF_UP));
//                Double money = new BigDecimal(Double.parseDouble(String.valueOf(tenTenantMoney)),2);
            }
        Map sixMap = new HashMap();
        sixMap.put("tenTenantName",tenTenantName);
        sixMap.put("tenTenantMoney",tenTenantMoney);

        allMap.put("modelsix",sixMap);

        return AjaxResult.success(allMap);
    }

    //        ==================================================租户人数一览=====================================================


    /**
     * 租户人数一览
     * @return
     */
    @PostMapping("/statDataTenantNum")
    @ResponseBody
    public AjaxResult statDataTenantNum() {
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM");
        SysTenant sysTenant = new SysTenant();
        sysTenant.setTenantStatus(TenantStatus.LIVEING.getCode());
        List<SysTenant> sysTenantsList = sysTenantService.selectSysTenantList(sysTenant);
        List<String> dateList = Arrays.asList("1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月");
        List buildingNumA = new ArrayList<Integer>();
        List buildingNumB= new ArrayList<Integer>();
        List buildingNumC= new ArrayList<Integer>();
        List buildingNumD= new ArrayList<Integer>();
        List buildingNumAll = new ArrayList<Integer>();
        Map map = new HashMap();


        for (String date : dateList) {
            int a = 0,b = 0,c=0, d=0,all= 0;
            for (SysTenant sysTenantsNum:sysTenantsList){
                if (sdf.format(sysTenantsNum.getStartTime()).compareTo(changeDate(date))<0
                        && sdf.format(sysTenantsNum.getEndTime()).compareTo(changeDate(date))>0){
                    all++;
                    if(sysTenantsNum.getBuildingName().equals("A")){
                        a++;
                    }
                    if(sysTenantsNum.getBuildingName().equals("B")){
                        b++;
                    }
                    if(sysTenantsNum.getBuildingName().equals("C")){
                        c++;
                    }
                    if(sysTenantsNum.getBuildingName().equals("D")){
                        d++;
                    }

                }
            }
            buildingNumA.add(a);
            buildingNumB.add(b);
            buildingNumC.add(c);
            buildingNumD.add(d);
            buildingNumAll.add(all);
        }
        map.put("dateList",dateList);
        map.put("buildingNumA",buildingNumA);
        map.put("buildingNumB",buildingNumB);
        map.put("buildingNumC",buildingNumC);
        map.put("buildingNumD",buildingNumD);
        map.put("buildingNumAll",buildingNumAll);

        return AjaxResult.success(map);

    }

    //       ================================================出租单元一览=======================================================



    @PostMapping("/statDataUnitAlready")
    @ResponseBody
    public AjaxResult statDataUnitAlready() {
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM");
        SysTenant sysTenant = new SysTenant();
        sysTenant.setTenantStatus(TenantStatus.LIVEING.getCode());
        List<SysTenant> sysTenantsList = sysTenantService.selectSysTenantList(sysTenant);
        List<String> dateList = Arrays.asList("1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月");
        List unitNumA = new ArrayList<Integer>();
        List unitNumB= new ArrayList<Integer>();
        List unitNumC= new ArrayList<Integer>();
        List unitNumD= new ArrayList<Integer>();
        List unitNumAll = new ArrayList<Integer>();
        Map map = new HashMap();


        for (String date : dateList) {
            int a = 0,b = 0,c=0, d=0,all= 0;
            for (SysTenant sysTenantsNum:sysTenantsList){
                if (sdf.format(sysTenantsNum.getStartTime()).compareTo(changeDate(date))<0      //判断租户是否是在在租合同时间内
                        && sdf.format(sysTenantsNum.getEndTime()).compareTo(changeDate(date))>0){
                    if(sysTenantsNum.getBuildingName().equals("A")){
                        for(int i = 0;i<sysTenantsNum.getUnitIdStr().length();i++){             //A栋出租单元户数
                            a++;
                        }
                    }
                    if(sysTenantsNum.getBuildingName().equals("B")){                            //B栋出租单元户数
                        for(int i = 0;i<sysTenantsNum.getUnitIdStr().length();i++){
                            b++;
                        }
                    }
                    if(sysTenantsNum.getBuildingName().equals("C")){                              //C栋出租单元户数
                        for(int i = 0;i<sysTenantsNum.getUnitIdStr().length();i++){
                            c++;
                        }
                    }
                    if(sysTenantsNum.getBuildingName().equals("D")){                            //D栋出租单元户数
                        for(int i = 0;i<sysTenantsNum.getUnitIdStr().length();i++){
                            d++;
                        }
                    }
                    all= a+b+c+d;                           //全区出租单元户数

                }
            }
            unitNumA.add(a);
            unitNumB.add(b);
            unitNumC.add(c);
            unitNumD.add(d);
            unitNumAll.add(all);
        }
        map.put("dateList",dateList);
        map.put("unitNumA",unitNumA);
        map.put("unitNumB",unitNumB);
        map.put("unitNumC",unitNumC);
        map.put("unitNumD",unitNumD);
        map.put("unitNumAll",unitNumAll);

        return AjaxResult.success(map);

    }

    //       ================================================涨租情况一览=======================================================
//
    @PostMapping("/statDataHighStat")
    @ResponseBody
    public AjaxResult statDataHighStat() {
        Map map = new HashMap();
        List<Double> highNum = new ArrayList<>();
        List<Integer> highTenantNum = Arrays.asList(0,0,0,0,0,0,0,0,0,0,0,0,0,0);
        List<SysHigher> highTenantNumList= sysHigherService.selectSysHigherStatNum();
        List<String> dateList = Arrays.asList("1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月");
        for (String date :dateList) {       //循环遍历月份
            Double number = sysHigherService.selectSysHigherStat(changeDateTwo(date));//获取涨租金额
            if(number==null)
            {
                number=0D;
            }
            highNum.add(number);
        }
        for (SysHigher higher:highTenantNumList){
            if(higher.getStatTime()!=null){
                highTenantNum.set(changDate(higher.getStatTime())-1,Integer.parseInt(higher.getNumber()));
            }
            else {
                highTenantNum.set(0,0);
            }
        }
        map.put("highTenantNum",highTenantNum);
        map.put("dateList",dateList);
        map.put("highNum",highNum);
        return AjaxResult.success(map);

    }




}









